
import React from 'react';
import {inject,observer} from 'mobx-react';
import {toJS} from 'mobx';
import { withRouter } from 'react-router-dom';
import { Tools, Tag, Icon, Modal, Flex, Toast } from 'weaver-mobile';
import TopBar from './topBar.js';

const allStore =[
  'esearchStore',
]
const getLabel = Tools.getLabel;
const alert = Modal.alert;

@inject(...allStore)
@withRouter
@observer
export default class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      searchBarType: getLabel(82857,'全部'),
      contentType: 'ALL',
      perORsysVisible: true,
      value: '',
      pIndex: 1,
      pagesize: 20,
      changeType:false,
      hideTitle: false,
    }
  }

  getTags = (describe, tab) => {
    let { perHot, sysHot, baseDatas, onSearchClick, setParams } = this.props.esearchStore;
    baseDatas = toJS(baseDatas);
    let hasSys = true, hasPer = true;
    if(baseDatas.hotKey && baseDatas.hotKey.hasSys !== undefined) {
      hasSys = baseDatas.hotKey.hasSys;
    }
    if(baseDatas.hotKey && baseDatas.hotKey.hasPer !== undefined) {
      hasPer = baseDatas.hotKey.hasPer;
    }
    let field = [];
    let label = '';
    let hotType = [];
    if(tab === 1) { // 系统热点
      label = getLabel(83445,'看看大家都在搜什么');
      hotType = sysHot;
    }
    if(tab === 2) {
      if(sysHot) {
        if((sysHot.length === 0) || (perHot&&perHot.length === 0)) return;
        label = getLabel(391115,'我经常搜索的');
        hotType = perHot;
      }else{
        label = getLabel(391115,'我经常搜索的');
        hotType = perHot;
      }
    }
    if(hotType) {
      field.push(
        <div className='tag-title-describe' key='tag-title-describe'><span>{describe}</span><label>{label}</label></div>
      );
      field.push(
        <div className="tag-container" key='tag-container'>
          {
            hotType.length === 0 ? <label className='no-hot'>{getLabel(391116,'暂无热点')}</label> : hotType.map((item,index) => {
              return (<Tag key={index} prefixCls={'am-tag-normal'} onChange={() => {
                // this.onTagChange(item, 'enter');
                const { search } = this.props.location;
                onSearchClick('enter', { keyword: item }, this.props.history, search);
                setParams({ tagParams: {} });
              }}>{item}</Tag>)
            })
          }
        </div>
      )
    }
    if(tab === 1 && hasSys) return field;
    if(tab === 2 && hasPer) return field;
  }

  delModal = (title, msg, ok, oncancel) => {
    alert(' ', getLabel('524271','确定要清空历史搜索记录吗？') , [
      { text: getLabel(31129,'取消'), onPress: () => {
        typeof oncancel === 'function' && oncancel();
      }},
      { text: getLabel(826,'确定'), onPress: () => {
        typeof ok === 'function' && ok();
      }},
    ])
  }

  delHistory = () => {
    const { delHistorySearch, getCustompageBaseDatas } = this.props.esearchStore;
    this.delModal('', getLabel('524271','确定要清空历史搜索记录吗？') , () => {
      delHistorySearch({ forAll: 1 }, () => {
        getCustompageBaseDatas({
          cuspage_type: '2'
        });
      });
    });
  }

  getLoading = () => {
    return <div className='esearch-loading'>
      <Icon type='loading' size='lg'/>
    </div>
  }

  filterParams = () => {
    let { browserKeyArr, extraForm } = this.props.esearchStore;
    const formParams = extraForm.formParams;
    let search_json = { ...formParams };
    
    delete search_json.showorder;
    delete search_json.tagName;
    delete search_json.tagTitle;
    browserKeyArr = toJS(browserKeyArr);

    Object.keys(search_json).forEach(key => {
      let json = toJS(search_json[key]);
      if(typeof json === 'object') { // 过滤obj
        let objA = { ...search_json[key] };
        search_json = {
          ...search_json,
          ...objA
        };
      } 
      if(browserKeyArr.some(v => v === key)) {
        if(search_json[key] !== '') {
          search_json[key] = search_json[key].split(',');
        } else {
          delete search_json[key];
        }
      }

      browserKeyArr.forEach(v => {// 过滤浏览按钮span
        if(key.indexOf('span') > -1 && key.indexOf(v) > -1) {
          delete search_json[key];
        }
      });
 
      if(search_json[key] === '') {// 过滤''值
        delete search_json[key];
      }
    });
    if(search_json.CREATERID !== undefined && search_json.CREATERID !== '') {
      search_json = {
        ...search_json,
        CREATERID_select: '2'
      };
    }

    return search_json;
  }

  render() {
    let { contentType, setParams, commonSetLayout, getCustompageBaseDatas, topbarVisible,
      onSearchClick, homeBaseDatas, baseDatas:{tagList, historySearchList}, baseDatas, initLoading, getAdvancedForm
    } = this.props.esearchStore;
    const { changeType } = this.state;
    //需要渲染模块名称
    if(changeType){
      const tempcontentType=this.state.contentType;
      contentType.forEach(element => {
        element=toJS(element)
        if(element.key===tempcontentType){
          this.setState({searchBarType:element.name,changeType:false});
        }
      });
    }

    contentType = toJS(contentType);

    const { search } = this.props.location;
    if(initLoading) {
      return this.getLoading();
    }
    return (
      <div className="esearch-home">
        { baseDatas && baseDatas.FLAG === '-1' && Toast.offline(baseDatas.MSG.replace(/<\/?span>/g,''), 24*3600) }
        <TopBar />
        <div className='search-list-container' ref='seaList' style={{overflowX:'auto',WebkitOverflowScrolling: 'touch', top: topbarVisible ? 90 : 45 }}
          // onScroll={this.onscroll}
        >
          {homeBaseDatas.page_showHistory && <TagItems 
            domkey='historicalSearch'
            describe={getLabel('503436','历史搜索')}
            nodatamsg={getLabel('524269','暂无搜索记录') }
            data={historySearchList}
            icon={<Icon type="delete"/>}
            onIconClick={this.delHistory}
            onTagClick={(item) => {
              const { search } = this.props.location;
              onSearchClick('enter', { keyword: item.name }, this.props.history, search);
              setParams({ tagParams: {} });
            }}
          />}
          {homeBaseDatas.page_showCommonConditions && <TagItems 
            domkey='commonContitions'
            describe={getLabel('32905','常用条件') }
            nodatamsg={getLabel('524270','暂无搜索条件') }
            data={tagList}
            icon={<Icon type="setting-up"/>}
            onIconClick={() => { 
              getCustompageBaseDatas({ cuspage_type: '3', showHideTag: 1 }, () => {
                this.props.history.push(`${commonSetLayout.path}${search}`);
              });
            }}
            onTagClick={(item) => {
              const { search } = this.props.location;
              onSearchClick('enter', { keyword: item.searchKey, searchTagId: item.key || '' }, this.props.history, search);
              setParams({ tagParams: item });
              getAdvancedForm({ search_json: JSON.stringify(this.filterParams()), id: item.key || '' });
            }}
          />}
          {this.getTags(getLabel(81783,'系统热点'),1)}
          {this.getTags(getLabel(81784,'个人热点'),2)}
        </div>
      </div>
    );
  }
}

function TagItems(props) {
  const { domkey, icon, describe, describeLabel, nodatamsg } = props;
  let { data } = props;
  let field = [];
  const classname = 'esearch-tag-container';
  data = toJS(data);
  field.push(
    <div className={`${classname}-header`} key='tag-title-describe'>
      <span className="tag-describe">{describe}</span>
      <label className="tag-label">{describeLabel}</label>
      <span className="tag-extra" onClick={() => {
        typeof props.onIconClick === 'function' && props.onIconClick();
      }}>{icon}</span>
    </div>
  );
  let nodatasBool = true;
  if(data && data.length === 0) {
    nodatasBool = true;
  } else {
    nodatasBool = false;
    if(domkey=== 'commonContitions') { // 常用条件过滤隐藏
      let bool = true;
      data && data.forEach(element => {
        if(element.enable === '0') {
          bool = bool*true;
        } else {
          bool = bool*false;
        }
      });
      nodatasBool = bool;
    }
  }
  field.push(
    <div className={`${classname}-content`} key='tag-container'>
      {
        nodatasBool ? <label className='no-hot'>{ nodatamsg }</label> : data&&data.map((item,index) => {
          if(item.enable === '0') return;
          return (<Tag key={index} prefixCls={'am-tag-normal'} onChange={() => { typeof props.onTagClick === 'function' && props.onTagClick(item, 'enter'); }}>{item.name}</Tag>)
        })
      }
    </div>
  )
  return (
    <Flex className={`${classname} ${domkey}`}>
      { field }
    </Flex>
  );
}